package org.neowei.image.filtering.handle;

import java.awt.image.BufferedImage;

import org.neowei.image.api.ImageOption;
import org.neowei.image.filter.Filter;
import org.neowei.image.filter.FilterOption;
import org.neowei.image.filtering.HorizontalFiltering;
import org.neowei.image.filtering.VerticalFiltering;

public class CropResizeHandle implements IHandle {

	@Override
	public BufferedImage getBufferedImage(ImageOption imageOption, BufferedImage srcimage) {
		if (imageOption.getNeowidth() == 0 && imageOption.getNeoheight() == 0) {
			return srcimage;
		} else if (imageOption.getNeowidth() < imageOption.getNeoheight()) {
			int rwidth = imageOption.getNeoheight() * imageOption.getSrcwidth() / imageOption.getSrcheight();
			System.out.println(rwidth);
			FilterOption contributor = Filter.getContrib(rwidth, imageOption.getSrcwidth());
			BufferedImage horbuffer = new HorizontalFiltering(contributor, imageOption.getSrcwidth(), imageOption.getSrcheight(), rwidth, srcimage).getBufferedImage();
			BufferedImage outimage = new VerticalFiltering(contributor, imageOption.getSrcheight(), rwidth, imageOption.getNeoheight(), horbuffer).getBufferedImage();
			return outimage.getSubimage((rwidth - imageOption.getNeowidth()) / 2, 0, imageOption.getNeowidth(), imageOption.getNeoheight());
		} else {
			int rheight = imageOption.getNeowidth() * imageOption.getSrcheight() / imageOption.getSrcwidth();
			System.out.println(rheight);
			FilterOption contributor = Filter.getContrib(imageOption.getNeowidth(), imageOption.getSrcwidth());
			BufferedImage horbuffer = new HorizontalFiltering(contributor, imageOption.getSrcwidth(), imageOption.getSrcheight(), imageOption.getNeowidth(), srcimage).getBufferedImage();
			BufferedImage outimage = new VerticalFiltering(contributor, imageOption.getSrcheight(), imageOption.getNeowidth(), rheight, horbuffer).getBufferedImage();
			return outimage.getSubimage(0, (rheight - imageOption.getNeoheight()) / 2, imageOption.getNeowidth(), imageOption.getNeoheight());
		}

	}
}
